<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import { Button, Card, Modal, Space, Table, Tag } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';

import {
  disableModel,
  discoverModels,
  enableModel,
  fetchModelByCode,
  fetchParametersByModelId,
  fetchParametersByModelIdReflection,
  listDiscoveredModels
} from '@/service/api/valuation';

// 通用：兼容后端返回数据被 request.transformBackendResponse 处理后（直接返回data），或未处理（包裹在data字段）
function unwrapData<T = any>(resp: any): T | null {
  if (resp === null || resp === undefined) return null as any;
  // 如果已经是数组或对象，且不含有 code/msg 等字段，默认就是数据本体
  if (Array.isArray(resp)) return resp as any;
  if (typeof resp === 'object' && !('code' in resp) && !('msg' in resp) && !('data' in resp)) return resp as any;
  // 包裹在 data
  if (resp && typeof resp === 'object' && 'data' in resp) return resp.data as any;
  return null as any;
}

// 通用：数组数据解包
function unwrapList<T = any>(resp: any): T[] {
  const data = unwrapData<T[] | T>(resp);
  if (Array.isArray(data)) return data as T[];
  return [];
}

// 数据状态
const loading = ref(false);
const tableData = ref<any[]>([]);

// 模态框状态
const modalVisible = ref(false);
const modalTitle = ref('新增模型');
const isEdit = ref(false);
const showParameterModal = ref(false);
const currentModelName = ref('');
const modelParameters = ref<any[]>([]);

// 移除筛选功能，因为只显示发现的模型

// 表单数据
const formData = reactive<any>({
  name: '',
  code: '',
  modelType: undefined,
  implementationClass: '',
  version: '',
  description: '',
  status: true
});

// 表格列定义
const columns: TableColumnsType = [
  {
    title: '模型名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '模型编码',
    dataIndex: 'code',
    key: 'code',
    width: 150
  },
  {
    title: '模型类型',
    dataIndex: 'modelType',
    key: 'modelType',
    width: 120
  },
  {
    title: '实现类',
    dataIndex: 'implementationClass',
    key: 'implementationClass',
    width: 200,
    ellipsis: true
  },
  {
    title: '版本',
    dataIndex: 'version',
    key: 'version',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 220,
    fixed: 'right'
  }
];

// 加载模型列表（显示已发现的模型）
async function loadModels() {
  try {
    loading.value = true;
    const resp = await listDiscoveredModels();
    tableData.value = unwrapList<any>(resp);
  } catch (error) {
    console.error('加载模型失败:', error);
    window.$message?.error('加载模型失败');
  } finally {
    loading.value = false;
  }
}

// 触发扫描并注册模型
async function handleDiscoverModels() {
  try {
    loading.value = true;
    const resp = await discoverModels();
    const list = unwrapList<any>(resp);
    window.$message?.success(`已同步${list.length}个模型`);
    // 直接使用同步返回的数据更新表格，这些模型已经有了有效的ID
    tableData.value = list;
  } catch (error) {
    console.error('模型自动发现失败:', error);
    window.$message?.error('模型自动发现失败');
  } finally {
    loading.value = false;
  }
}

// 函数已移除，使用loadModels代替

// // 打开新增模态框
// function openAddModal() {
//   modalTitle.value = '新增模型';
//   isEdit.value = false;
//   resetForm();
//   modalVisible.value = true;
// }

// 打开编辑模态框
async function openEditModal(record: any) {
  modalTitle.value = '编辑模型';
  isEdit.value = true;

  try {
    const resp = await fetchModelByCode(record.code!);
    const data = unwrapData<any>(resp);
    if (data) {
      Object.assign(formData, data);
    } else {
      // 兜底：如果没查到，使用当前记录回填
      Object.assign(formData, record);
    }
  } catch (error) {
    console.error('获取模型详情失败:', error);
    window.$message?.warning('未从后端获取到模型详情，已使用当前行数据作为回填');
    Object.assign(formData, record);
  }

  modalVisible.value = true;
}

// 查看模型参数
async function handleViewParameters(record: any) {
  currentModelName.value = record.name;

  // 检查模型是否有有效的ID
  const modelId = record.id;
  if (!modelId) {
    window.$message?.warning('该模型尚未同步到数据库，无法查看参数');
    return;
  }

  try {
    // 首先尝试通过反射接口获取参数
    const reflectionResponse = await fetchParametersByModelIdReflection(modelId);
    const reflectionData = unwrapList<any>(reflectionResponse);
    if (reflectionData && reflectionData.length > 0) {
      modelParameters.value = reflectionData;
    } else {
      // 如果反射接口没有返回参数，则尝试数据库接口
      const dbResponse = await fetchParametersByModelId(modelId);
      modelParameters.value = unwrapList<any>(dbResponse);
    }
    showParameterModal.value = true;
  } catch (error) {
    console.error('获取模型参数失败:', error);
    window.$message?.error('获取模型参数失败');
  }
}

// 上线模型
function handleEnableModel(record: any) {
  window.$modal?.confirm({
    title: '确认上线',
    content: `确定要上线模型「${record.name}」吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await enableModel(record.id);
        window.$message?.success('模型已上线');
        await loadModels(); // 重新加载列表
      } catch (error) {
        console.error('上线模型失败:', error);
        window.$message?.error('上线模型失败');
      }
    }
  });
}

// 下线模型
function handleDisableModel(record: any) {
  window.$modal?.confirm({
    title: '确认下线',
    content: `确定要下线模型「${record.name}」吗？下线后该模型将无法使用。`,
    okText: '确认',
    cancelText: '取消',
    okType: 'danger',
    async onOk() {
      try {
        await disableModel(record.id);
        window.$message?.success('模型已下线');
        await loadModels(); // 重新加载列表
      } catch (error) {
        console.error('下线模型失败:', error);
        window.$message?.error('下线模型失败');
      }
    }
  });
}

onMounted(() => {
  loadModels();
});
</script>

<template>
  <div class="model-management">
    <Card>
      <template #title>
        <div class="flex items-center justify-between">
          <span>模型管理</span>
          <div class="flex items-center gap-2">
            <Button class="flex items-center" @click="loadModels">
              <icon-carbon:search class="mr-1 text-base" />
              查看可发现模型
            </Button>
            <Button type="primary" ghost class="flex items-center" @click="handleDiscoverModels">
              <icon-carbon:cloud-download class="mr-1 text-base" />
              同步后端实现的模型
            </Button>
            <!--
 <Button type="primary" class="flex items-center" @click="openAddModal">
              <icon-carbon:add class="mr-1 text-base" />
              新增模型
            </Button> 
-->
          </div>
        </div>
      </template>

      <!-- 移除筛选条件，只显示发现的模型 -->

      <Table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :row-key="(record: any) => record.id ?? record.code ?? record.implementationClass"
        :scroll="{ x: 1000 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="record.status !== false ? 'green' : 'red'">
              {{ record.status !== false ? '启用' : '禁用' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button size="small" @click="openEditModal(record)">编辑</Button>
              <Button size="small" type="primary" ghost @click="handleViewParameters(record)">查看参数</Button>
              <Button
                v-if="record.status === false"
                size="small"
                type="primary"
                :disabled="!record.id"
                @click="handleEnableModel(record)"
              >
                <icon-carbon:play class="mr-1" />
                上线
              </Button>
              <Button v-else size="small" danger :disabled="!record.id" @click="handleDisableModel(record)">
                <icon-carbon:stop class="mr-1" />
                下线
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 查看参数模态框 -->
    <Modal
      v-model:open="showParameterModal"
      :title="`${currentModelName} - 模型参数`"
      width="800px"
      :footer="null"
      @cancel="showParameterModal = false"
    >
      <Table
        :columns="[
          { title: '参数名称', dataIndex: 'name', key: 'name' },
          { title: '参数类型', dataIndex: 'type', key: 'type' },
          { title: '是否必填', dataIndex: 'required', key: 'required' },
          { title: '默认值', dataIndex: 'defaultValue', key: 'defaultValue' },
          { title: '描述', dataIndex: 'description', key: 'description' }
        ]"
        :data-source="modelParameters"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'required'">
            <Tag :color="record.required ? 'red' : 'green'">
              {{ record.required ? '必填' : '可选' }}
            </Tag>
          </template>
        </template>
      </Table>
    </Modal>
  </div>
</template>

<style scoped>
.model-management {
  padding: 24px;
}

.filter-section {
  padding: 16px;
  background: var(--ant-fill-tertiary);
  border-radius: 6px;
  border: 1px solid var(--ant-border-color-split);
}

/* 暗色主题下的样式 */
.dark .filter-section {
  background: #2a2a2a;
  border: 1px solid #404040;
}

@media (max-width: 768px) {
  .model-management {
    padding: 16px;
  }

  .filter-section .grid {
    grid-template-columns: 1fr;
  }
}
</style>
